package com.mccken.thread;

import java.util.Map;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @program: mccken-collect
 * @description:
 * @author: mccken
 * @create: 2024-03-20 22:05
 **/
public class MyTreadPoolFactory {

	private static final Map<String, MyThreadPoolExecutor> executorMap = new ConcurrentHashMap<>();

	public static MyThreadPoolExecutor getThreadPool(String name) {
		return executorMap.computeIfAbsent(name,
				(key) -> doCreateThreadPoolExecutor(name));
	}

	private static MyThreadPoolExecutor doCreateThreadPoolExecutor(String name) {
		return new MyThreadPoolExecutor(5, 10, 5,
				TimeUnit.MINUTES, new LinkedBlockingQueue<>(3000), new BuzThreadFactory(name), name);
	}

	static class BuzThreadFactory implements ThreadFactory {
		private static final AtomicInteger poolNumber = new AtomicInteger(1);
		private final ThreadGroup group;
		private final AtomicInteger threadNumber = new AtomicInteger(1);
		private final String namePrefix;

		BuzThreadFactory(String threadName) {
			SecurityManager s = System.getSecurityManager();
			this.group = (s != null) ? s.getThreadGroup() :
					Thread.currentThread().getThreadGroup();
			namePrefix = "buz-biz-" + threadName + "-pool-" +
					poolNumber.getAndIncrement() +
					"-thread-";
		}

		@Override
		public Thread newThread(Runnable r) {
			Thread thread = new Thread(group, r, namePrefix + threadNumber.getAndIncrement(), 0);
			if (thread.getPriority() != Thread.NORM_PRIORITY)
				thread.setPriority(Thread.NORM_PRIORITY);
			return thread;
		}
	}

	public static void threadPoolStatus(MyThreadPoolExecutor executor) {
		BlockingQueue<Runnable> queue = executor.getQueue();
		System.out.println(
				"线程池：" + executor.getName() +
						" 活动线程数：" + executor.getActiveCount() +
						" 核心线程数：" + executor.getCorePoolSize() +
						" 最大线程数：" + executor.getMaximumPoolSize() +
//						" 线程池活跃度：" + divide(executor.getActiveCount(), executor.getMaximumPoolSize()) +
						" 任务完成数：" + executor.getCompletedTaskCount() +
						" 队列堆积：" + queue.size() +
						" 队列大小：" + (queue.size() + queue.remainingCapacity()) +
						" 队列剩余大小：" + queue.remainingCapacity()
//						+ " 队列使用度：" + divide(queue.size(), queue.size() + queue.remainingCapacity())
		);
	}

}
